
package com.x52im.rbchat.logic.chat_group.at;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 当前被@ 人的数据管理模型。
 *
 * @author JackJiang
 * @since 11.0
 */
public class AtModel {

    /** 已@ 的成员 */
    private Map<String, AtBlock> atBlocks = new HashMap<>();

    /**
     * 清除所有的@块。
     */
    public void reset() {
        atBlocks.clear();
    }

    public void addAtUser(String account, String name, int start) {
        AtBlock atBlock = atBlocks.get(account);
        if (atBlock == null) {
            atBlock = new AtBlock(name);
            atBlocks.put(account, atBlock);
        }
        atBlock.addSegment(start);
    }

    /**
     * 查所有被@的群成员。
     *
     * @return
     */
    public List<String> getAtUsers() {
        List<String> users = new ArrayList<>();
        Iterator<String> iterator = atBlocks.keySet().iterator();
        while (iterator.hasNext()) {
            String account = iterator.next();
            AtBlock block = atBlocks.get(account);
            if (block.valid()) {
                users.add(account);
            }
        }
        return users;
    }

    /**
     * 找到 curPos 恰好命中 end 的segment。
     *
     * @param start
     * @return
     */
    public AtBlock.AtSegment findAtSegmentByEndPos(int start) {
        Iterator<String> iterator = atBlocks.keySet().iterator();
        while (iterator.hasNext()) {
            String account = iterator.next();
            AtBlock block = atBlocks.get(account);
            AtBlock.AtSegment segment = block.findLastSegmentByEnd(start);
            if (segment != null) {
                return segment;
            }
        }
        return null;
    }

    /**
     * 文本插入后更新@块的起止位置。
     *
     * @param start
     * @param changeText
     */
    public void onInsertText(int start, String changeText) {
        Iterator<String> iterator = atBlocks.keySet().iterator();
        while (iterator.hasNext()) {
            String account = iterator.next();
            AtBlock block = atBlocks.get(account);
            block.moveRight(start, changeText);
            if (!block.valid()) {
                iterator.remove();
            }
        }
    }

    /**
     * 文本删除后更新@块的起止位置。
     *
     * @param start
     * @param length
     */
    public void onDeleteText(int start, int length) {
        Iterator<String> iterator = atBlocks.keySet().iterator();
        while (iterator.hasNext()) {
            String account = iterator.next();
            AtBlock block = atBlocks.get(account);
            block.moveLeft(start, length);
            if (!block.valid()) {
                iterator.remove();
            }
        }
    }
}
